# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :qiniu_upload.py
# @Time      :2022/7/11 18:43
# @Author    :吕华龙
from eventlet.green._socket_nodns import os
from qiniu import Auth, put_file, etag
from flask import current_app


class QiniuTool:
    q = None

    def __init__(self):
        ak = "icLlrc9a9eOKxWd9oWWfxrSfCXrGM0Glx7WcdL8e"
        sk = "cMI-8TFzJsGJ3OUPm3jPko5W56qo8T4FtItStAbk"
        self.q = Auth(ak, sk)

    def upload_file(self, localfile, new_file):
        # 要上传的空间
        bucket_name = 'lvhualong1'

        # 上传后保存的文件名
        key = new_file

        # 生成上传 Token，可以指定过期时间等
        token = self.q.upload_token(bucket_name, key, 3600)
        # 要上传文件的本地路径
        ret, info = put_file(token, key, localfile, version='v2')
        print("----ret", ret)
        print("----info", info)
        assert ret['key'] == key
        assert ret['hash'] == etag(localfile)

        return current_app.config["QINIU_HOST"] + ret['key']


if __name__ == '__main__':
    from app import app

    with app.app_context():
        q = QiniuTool()
        file_path = os.path.join(os.path.abspath("./../"), "static/logo01.png")
        file_name = q.upload_file(file_path, "000000.jpg")
        print(file_name)
